package com.android.readcard.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.android.readcard.R;
import com.android.readcard.adapter.BleAdapter;
import com.android.readcard.bean.BackReadInfo;
import com.android.readcard.bean.CardData;
import com.android.readcard.bean.ReadCardInfo;
import com.android.readcard.dialog.MyUsualyDialog;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.android.readcard.global.ConstantsValue;
import com.android.readcard.global.PrefReadCardTools;
import com.android.readcard.inter.UpLoadListener;
import com.android.readcard.read.DjlmConnectUtils;
import com.android.readcard.read.HengHongDaConnectUtils;
import com.android.readcard.read.HuaShiConnectUtils;
import com.android.readcard.read.Kt8000ConnectUtils;
import com.android.readcard.read.Kt8003ConnectUtils;
import com.android.readcard.read.SenRuiConnectUtils;
import com.android.readcard.read.XinTongConnectUtils;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.GlobReadCardUtils;
import com.android.readcard.utils.ToastUtils;
import com.android.readcard.utils.blluetooth.BluetoothManager;
import com.kaer.sdk.bt.BtReadClient;
import com.kaeridcard.client.BtReaderClient;

import java.util.ArrayList;
import java.util.Set;

/**
 * 店家联盟读卡参数在项目里面获取传值进来
 */
public class BleActivity extends CardBaseActivity implements UpLoadListener {

    private Set<BluetoothDevice> pairedDevices;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble);
        initView();
        initData(); // 初始化数据,获取读卡参数
    }

    private void initView() {
        lv_ble = findViewById(R.id.lv_ble);
        pb_ble = findViewById(R.id.pb_ble);
        ll_shebei = findViewById(R.id.ll_shebei);

        myUsualyDialog = new MyUsualyDialog(BleActivity.this, R.layout.wait_item);
        myUsualyDialog.setCanceledOnTouchOutside(true);
        myUsualyDialog.setCancelable(false);
        ba = BluetoothAdapter.getDefaultAdapter();

        itemClick();
        stopRead();
    }

    /**
     * 条目点击事件
     */
    private void itemClick() {
        lv_ble.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                ll_shebei.setVisibility(View.GONE);
                mHandler.sendEmptyMessage(0);

                bleName = bleNameList.get(position);
                bleAddress = bleAddressList.get(position);
                remoteDevice = ba.getRemoteDevice(bleAddress);

                int readType = quFenReadSheBei(bleName);

                // 获取读卡参数
                getReadNum(readType);
                Log.e("蓝牙异常", bleName + "====获取读卡参数=====:" + bleAddress);
                if (readType == 0 || readType == 6) {
                    // 华视,店家联盟直接读卡
                    searchSuc(readType, bleAddress, bleName, remoteDevice);
                } else {
                    Log.e("蓝牙异常", bleName + "====获取读卡参数=====:" + strPeiDuiNam);
                    // 如果不是华视和店家联盟,就要判断是否已配对
                    if (strPeiDuiNam.contains(bleName)) {
                        searchSuc(readType, bleAddress, bleName, remoteDevice);
                    } else {
                        BleGlobUtils.setDialog(BleActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 区分是那种读卡器
     *
     * @param bleStrName 返回读卡器类型
     * @return
     */
    private int quFenReadSheBei(String bleStrName) {
        if (bleStrName.contains("KT8000")) {
            index = 1;
            bluetoothName = "卡尔KT8000读卡";
        } else if (bleStrName.contains("KT8003")) {
            index = 2;
            bluetoothName = "卡尔KT8003读卡";
        } else if (bleStrName.contains("SS")) {
            index = 3;
            bluetoothName = "神思读卡";
        } else if (bleStrName.contains("SR")) {
            index = 4;
            bluetoothName = "森锐读卡";
        } else if (bleStrName.contains("HOD")) {
            index = 5;
            bluetoothName = "恒鸿达读卡";
        } else if (bleStrName.contains("DJLM")) {
            mHandler.sendEmptyMessage(0); // 取消搜索
            index = 6;
            bluetoothName = "店家联盟读卡";
        } else if (bleStrName.contains("ST710")) {
            index = 7;
            bluetoothName = "信通读卡";
        } else if (bleStrName.contains("CVR")) {
            // 华视读卡
            index = 0;
            bluetoothName = "华视读卡";
        } else {
            // 华视读卡(华视读卡器名称不一致,无法规律化)
            index = 0;
            bluetoothName = "华视读卡";
        }
        return index;
    }

    private static final int REQUEST_CODE_BLUETOOTH_ON = 1313;
    /**
     * Bluetooth 设备可见时间，单位：秒。
     */
    private static final int BLUETOOTH_DISCOVERABLE_DURATION = 250;

    // 初始化数据
    private void initData() {
        if (BluetoothManager.isBluetoothSupported()) {
            if (!BluetoothManager.isBluetoothEnabled()) {
                turnOnBluetooth();
            } else {
                searchBt();
            }
        }
    }

    /**
     * 弹出系统弹框提示用户打开 Bluetooth
     */
    private void turnOnBluetooth() {
        // 请求打开 Bluetooth
        Intent requestBluetoothOn = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);

        // 设置 Bluetooth 设备可以被其它 Bluetooth 设备扫描到
        requestBluetoothOn
                .setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // 设置 Bluetooth 设备可见时间
        requestBluetoothOn.putExtra(
                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                BLUETOOTH_DISCOVERABLE_DURATION);

        // 请求开启 Bluetooth
        this.startActivityForResult(requestBluetoothOn,
                REQUEST_CODE_BLUETOOTH_ON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // requestCode 与请求开启 Bluetooth 传入的 requestCode 相对应
        Log.e("项目异常lanya", requestCode + "-----onActivityResult------" + resultCode);
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {
            if (resultCode==Activity.RESULT_CANCELED){
                finish();
            }else{
                initData();
            }
        }
    }

    /**
     * 获取读卡参数
     * 利用library里面的PrefUtils去app里面保存数据,不然获取不到数据
     */
    private void getReadNum(int readType) {
        switch (readType) {
            case 1:
            case 2:
                krServerIp = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.KRFTserverIp, "115.28.2.173");
                krAccount = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.KRFTaccount, "admin");
                krPassword = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.KRFTpassword, "www.kaer.cn");
                krftPort = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.KRFTport, "7443");
                Log.e("项目异常connect", "------krServerIp------" + krServerIp);
                break;
            case 4:
                srSeverIp = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.SRserverIp, "id.esaleb.com");
                srAccount = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.SRaccount, "test01");
                srPwd = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.SRpassword, "12315aA..1");
                srPort = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.SRport, "6100");
                srKey = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.SRkey, "FE870B0163113409C134283661490AEF");
                Log.e("项目异常connect", "------srSeverIp------" + srSeverIp);
                break;
            case 7:
                server_address = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.XTserverIp, "49.117.145.10");
                port = PrefReadCardTools.getString(BleActivity.this, ConstantsValue.XTport, "10002");
                server_port = Integer.parseInt(port);
                Log.e("项目异常connect", "------server_address------" + server_address);
                break;
        }
    }

    // 开始搜索
    private void startSeach() {
        bleNameList = new ArrayList<>();
        bleAddressList = new ArrayList<>();
        bleAdapter = new BleAdapter(BleActivity.this, bleNameList);
        lv_ble.setAdapter(bleAdapter);

        // 配对搜索
        SearchBts();
    }
    //***********************************************搜索**************************************************

    /**
     * 开始搜索
     */
    public void searchBt() {
        // kt8003部分读卡器提前初始化一些数据
        mBtReadClient = BtReadClient.getInstance();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int krPort = Integer.parseInt(krftPort);
                int result = mBtReadClient.init(BleActivity.this, krServerIp,
                        krPort, krAccount, GlobReadCardUtils.getMD5(krPassword.getBytes()), true);
                mHandler.obtainMessage(900, result, result).sendToTarget();
            }
        }).start();
        startSeach(); // 开始搜索蓝牙
    }

    private String strNam = ""; // 判断是否已添加
    private String strPeiDuiNam = "";  // 判断配对列表

    /**
     * 搜索已配对蓝牙
     */
    private void SearchBts() {
        pb_ble.setVisibility(View.VISIBLE);
        pairedDevices = ba.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                strNam += device.getName();
                strPeiDuiNam += device.getName();
                String blueName = device.getName();
                String blueAddress = device.getAddress();

                // 检测配对设备,如果包含制定字符串就去连接读卡器
                bleNameList.add(blueName);
                bleAddressList.add(blueAddress);
                bleAdapter.notifyDataSetChanged();

                if (bleNameList.size() == pairedDevices.size()) {
                    // 附近蓝牙搜索
                    scanLeDevice(true);
                }
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    pb_ble.setVisibility(View.GONE);
                    ba.stopLeScan(mLeScanCallback);
                    break;
                case 1:
                    String err = (String) msg.obj;
                    Log.e("读卡结果", "------err------" + err);
                    if (!TextUtils.isEmpty(err)) {
                        ToastUtils.showShortToast(BleActivity.this, err);
                    }
                    if (myUsualyDialog != null) {
                        myUsualyDialog.dismiss();
                    }
                    finish();
                    break;
                case 2:
                    BluetoothDevice device = (BluetoothDevice) msg.obj;
                    pb_ble.setVisibility(View.VISIBLE);
                    Log.e("蓝牙异常", device.getName() + "搜索=====:" + device.getAddress());
                    mHandler.sendEmptyMessageDelayed(0, 6000);
                    String buleName = device.getName();
                    if (bleNameList != null) {
                        if (buleName != null && !TextUtils.isEmpty(buleName) && !"null".equals(buleName)) {
                            Log.e("蓝牙异常", "strNam=====:" + strNam);
                            if (!strNam.contains(buleName)) {
                                strNam += buleName; // 新增的继续拼接
                                // 如果蓝牙民称不包含就添加
                                Log.e("蓝牙异常", device.getName() + "=====添加=====:" + device.getAddress());
                                bleNameList.add(buleName);
                                bleAddressList.add(device.getAddress());
                                bleAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                    break;
            }
        }
    };

    private static final long SCAN_PERIOD = 8000;

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ba.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
            ba.startLeScan(mLeScanCallback);
        } else {
            pb_ble.setVisibility(View.GONE);
        }
    }

    /**
     * 搜索蓝牙(djlm)
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    Message message = new Message();
                    message.what = 2;
                    message.obj = device;
                    mHandler.sendMessage(message);
                }
            };

    //********************************************读卡**********************************************

    /**
     * 除开NFC和OTG的读卡连接
     *
     * @param readType
     * @param bleAddress
     * @param bleName
     * @param remoteDevice
     */
    private void searchSuc(final int readType, final String bleAddress, final String bleName, final BluetoothDevice remoteDevice) {
        myUsualyDialog.show();
        // 蓝牙搜索成功
        if (readType == 4) { // 森锐
            senRuiConnectUtils = new SenRuiConnectUtils(BleActivity.this,
                    bluetoothType, remoteDevice, bleName, bleAddress, bluetoothName, srAccount,
                    srPwd, srKey, BleActivity.this);
            senRuiConnectUtils.connect();
        } else if (readType == 7) {// 信通
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    Looper.prepare();
                    xinTongConnectUtils = new XinTongConnectUtils(BleActivity.this,
                            bluetoothType, bleName, bleAddress, bluetoothName, server_address,
                            port, BleActivity.this);
                    xinTongConnectUtils.connect();
                }
            }.start();
        } else {
            ConnectBt(readType, bleAddress, bleName, remoteDevice);
        }

    }

    // 连接读卡器
    public void ConnectBt(final int readType, final String bleAddress, final String bleName,
                          final BluetoothDevice remoteDevice) {

        new Thread() {
            @Override
            public void run() {
                super.run();
                Looper.prepare();
                switch (readType) {
                    case 0: // 华视
                        huaShiConnectUtils = new HuaShiConnectUtils(bluetoothType, ba, remoteDevice,
                                bleName, bleAddress, bluetoothName, BleActivity.this);
                        huaShiConnectUtils.connect();
                        break;
                    case 1: // KT8000
                        mClient = new BtReaderClient(BleActivity.this);
                        if (mClient != null) {
                            mClient.setCallBack(GlobReadCardUtils.mCallback);
                        }
                        kt8000ConnectUtils = new Kt8000ConnectUtils(bluetoothType, bleName, bleAddress,
                                bluetoothName, BleActivity.this);
                        kt8000ConnectUtils.connect(mClient);
                        break;
                    case 2: // KT8003
                        mClient = new BtReaderClient(BleActivity.this);
                        if (mClient != null) {
                            mClient.setCallBack(GlobReadCardUtils.mCallback);
                        }
                        kt8003ConnectUtils = new Kt8003ConnectUtils(bluetoothType, mBtReadClient,
                                remoteDevice, bleName, bleAddress, bluetoothName, BleActivity.this);
                        kt8003ConnectUtils.connect(mClient);
                        break;
                    case 3: // 神思
//                        shenSiConnectUtils = new ShenSiConnectUtils(BleActivity.this,
//                                bluetoothType, remoteDevice, bleName, bleAddress,
//                                bluetoothName, BleActivity.this);
//                        shenSiConnectUtils.connect();
                        mClient = new BtReaderClient(BleActivity.this);
                        if (mClient != null) {
                            mClient.setCallBack(GlobReadCardUtils.mCallback);
                        }
                        kt8000ConnectUtils = new Kt8000ConnectUtils(bluetoothType, bleName, bleAddress,
                                bluetoothName, BleActivity.this);
                        kt8000ConnectUtils.connect(mClient);
                        break;
                    case 5: // 恒鸿达
                        hengHongDaConnectUtils = new HengHongDaConnectUtils(BleActivity.this,
                                bluetoothType, remoteDevice, bleName, bleAddress,
                                bluetoothName, BleActivity.this);
                        hengHongDaConnectUtils.connect();
                        break;
                    case 6: // 店家联盟
                        djlmOrNfc(bleAddress, bleName, remoteDevice, false);
                        break;

                }
            }
        }.start();
    }

    private void djlmOrNfc(String bleAddress, String bleName, BluetoothDevice remoteDevice, boolean flag) {

        mClient = new BtReaderClient(BleActivity.this);
        if (mClient != null) {
            mClient.setCallBack(GlobReadCardUtils.mCallback);
        }
        djlmConnectUtils = new DjlmConnectUtils(BleActivity.this, bluetoothType, ba,
                remoteDevice, bleName, bleAddress, bluetoothName, BleActivity.this);
        djlmConnectUtils.connect(mClient, flag);
    }

    /**
     * 读卡成功
     *
     * @param info
     * @param cardData
     * @param chuanma
     */
    @Override
    public void onSucUpLoad(ReadCardInfo info, CardData cardData, String chuanma) {
        Log.e("读卡结果", "------ReadCardInfo------" + info.toString());
        Log.e("读卡结果", "------CardData------" + cardData.toString());
        Log.e("读卡结果", "------chuanma------" + chuanma);
        // 读卡成功
        setReadData(info, cardData, chuanma);
    }

    /**
     * 读卡失败
     *
     * @param bleType
     * @param err
     */
    @Override
    public void onErrUpLoad(int bleType, final String err) {
        // 读卡失败
        closeReadCard(bleType);
        Message message = new Message();
        message.what = 1;
        message.obj = err;
        mHandler.sendMessage(message); // 发送消息,弹出错误提示并关闭界面
    }

    /**
     * 终止读卡
     *
     * @param bleType
     */
    private void closeReadCard(int bleType) {
        switch (bleType) {
            case 0:
                if (huaShiConnectUtils != null) {
                    huaShiConnectUtils.stopConnect();
                }
                break;
            case 1:
                if (kt8000ConnectUtils != null) {
                    kt8000ConnectUtils.stopConnect();
                }
                break;
            case 2:
                if (kt8003ConnectUtils != null) {
                    kt8003ConnectUtils.stopConnect();
                }
                break;
            case 3:
                if (kt8000ConnectUtils != null) {
                    kt8000ConnectUtils.stopConnect();
                }
                break;
            case 4:
                if (senRuiConnectUtils != null) {
                    senRuiConnectUtils.stopConnect();
                }
                break;
            case 5:
                if (hengHongDaConnectUtils != null) {
                    hengHongDaConnectUtils.stopConnect();
                }
                break;
            case 6:
                if (djlmConnectUtils != null) {
                    djlmConnectUtils.stopConnect();
                }
                break;
            case 7:
                if (xinTongConnectUtils != null) {
                    xinTongConnectUtils.stopConnect();
                }
                break;

        }
    }

    /**
     * 设置数据,EventBus传递回去
     *
     * @param info
     * @param cardData
     */
    private void setReadData(ReadCardInfo info, CardData cardData, String chuanma) {
        if (myUsualyDialog != null) {
            myUsualyDialog.dismiss();
        }
        BackReadInfo backReadInfo = new BackReadInfo();
        backReadInfo.setInfo(info);
        backReadInfo.setCardData(cardData);
        backReadInfo.setChuanma(chuanma);
        Event<BackReadInfo> event = new Event<>(EventCodes.EventReadCardCode.A, backReadInfo);
        EventBusUtil.sendEvent(event);
        finish();
    }

    /**
     * 监听返回键和弹窗消失事件
     */
    public void stopRead() {
        myUsualyDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                finish();
            }
        });
        myUsualyDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                closeReadCard(index);
                myUsualyDialog.dismiss();
                return true;
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (senRuiConnectUtils != null) {
            senRuiConnectUtils.stopConnect();
        }
        super.onDestroy();
        bleNameList.clear();
        bleAddressList.clear();
        strNam = "";
        if (mLeScanCallback != null) {
            // 触发消失监听
            ba.stopLeScan(mLeScanCallback);
        }
    }
    //*************************************初始化*************************************************

    private HuaShiConnectUtils huaShiConnectUtils;
    private Kt8000ConnectUtils kt8000ConnectUtils;
    private Kt8003ConnectUtils kt8003ConnectUtils;
    private SenRuiConnectUtils senRuiConnectUtils;
    private HengHongDaConnectUtils hengHongDaConnectUtils;
    private XinTongConnectUtils xinTongConnectUtils;
    private DjlmConnectUtils djlmConnectUtils;

    // 卡尔参数
    private String krServerIp = "115.28.2.173";
    private String krAccount = "admin";
    private String krPassword = "www.kaer.cn";
    private String krftPort = "7443";

    // 森锐参数
    private String srSeverIp = "id.esaleb.com";
    private String srAccount = "test01";
    private String srPwd = "12315aA..1";
    private String srPort = "6100";
    private String srKey = "FE870B0163113409C134283661490AEF";

    // 信通参数
    private String server_address = "49.117.145.10";
    private String port = "10002";
    private int server_port = 0;


    //*******************************************************************************
    private BluetoothDevice remoteDevice;
    private ProgressBar pb_ble;
    private ArrayList<String> bleNameList = new ArrayList<>();
    private ArrayList<String> bleAddressList = new ArrayList<>();
    private BleAdapter bleAdapter;
    // 配对弹窗监听
    private ListView lv_ble;
    private LinearLayout ll_shebei;
    private String bleAddress;
    private String bleName;


    private MyUsualyDialog myUsualyDialog;
    private BtReaderClient mClient;
    private BtReadClient mBtReadClient;
    private BluetoothAdapter ba;

    private String bluetoothName = "";
    private String bluetoothType = "";
    private int index = 0;
}
